package com.ai.fupincore.service.common.impl;

import java.util.Map;
import java.util.UUID;

import com.ai.frame.bean.InputObject;
import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.fupincore.dao.impl.BaseDaoImpl;
import com.ai.fupincore.dynamicDataSoure.DynamicDataSourceHolder;
import com.ai.fupincore.service.common.ICacheService;
import com.ai.fupincore.util.DateUtil;
import com.ai.fupincore.util.StringUtil;
import com.ai.fupincore.util.DateUtil.DATE_PATTERN;
import com.ai.fupincore.util.DedicException;

import java.util.Date;

/**
 * 基础服务
 */
public class BaseServiceImpl {
	private static final Logger LOGGER = LoggerFactory.getServiceLog(BaseServiceImpl.class);
	private BaseDaoImpl baseDao;// 用户中心操作的dao
	private ICacheService cacheService;

	public BaseDaoImpl getBaseDao(InputObject inputObect) {
		getBaseDao(inputObect.getParams());
		return baseDao;
	}

	public BaseDaoImpl getBaseDao(Map<String, String> map) {
		getBaseDao(map.get("dataSource"));
		return baseDao;
	}
	
	public BaseDaoImpl getBaseDao(String dataSource) {
		LOGGER.info("当前数据源标示:", dataSource);
		DynamicDataSourceHolder.putDataSource(dataSource);
		return baseDao;
	}
	
	public BaseDaoImpl getBaseDao() {
		LOGGER.info("当前数据源标示:", DynamicDataSourceHolder.getDataSouce());
		return baseDao;
	}

	public void setBaseDao(BaseDaoImpl baseDao) {
		this.baseDao = baseDao;
	}

	public ICacheService getCacheService() {
		return cacheService;
	}

	public void setCacheService(ICacheService cacheService) {
		this.cacheService = cacheService;
	}


	/**
	 * 主键生成策略
	 * 
	 * @param tableName
	 *            需要获取主键的表名
	 */
	public String getSequence(String tableName) throws DedicException {
		if (StringUtil.isEmpty(tableName)) {
			throw new DedicException("获取主键时前缀不能为空!建议传入表名");
		}
		String redisKey = "REDIS_TBL_" + tableName;
		String id = null;
		try {
			LOGGER.info("开始获取主键 ", "key=" + redisKey);
			id = DateUtil.date2String(new Date(),
					DATE_PATTERN.YYYYMMDDHHMMSSSSS)
					+ ""
					//+ getCacheService().incr(redisKey)
					+(int)(Math.random()*90000+10000);
			LOGGER.info("获取主键成功", "id=" + id);
		} catch (Exception e) {
			LOGGER.error("使用redis获取主键失败，开始使用UUID", "key=" + redisKey, e);
			id = UUID.randomUUID().toString();
			LOGGER.error("NOT ERROR! 主键获取成功", "key=" + redisKey + ",id=" + id);
		}
		return id;
	}



}